#include<iostream>
#include<string>
#include<unistd.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<arpa/inet.h>
#include<netinet/in.h>
#include<cstring>

using namespace std;
enum Exit
{
    USAGE_ERROR=1,
    SOCKET_ERROR
};
enum class Status//c++11 强枚举类型：使用时需要带Status的作用域，而且会做语法检查
{
    NEW,//新建
    CONNECTING,//正在连接
    CONNECTED,//已经链接
    DISCONNECTED,//失联，通信中断开还没重连
    CLOSED//重联失败，链接关闭
};

static const int defaultsockfd=-1;
static const int defaultretryinterval=1;
static const int defaultmaxretries=5;
class ClientConnection
{
public:
    ClientConnection(string serverip,uint16_t port):
    _sockfd(defaultsockfd),
    _serverip(serverip),
    _serverport(port),
    _status(Status::NEW),
    _retry_interval(defaultretryinterval),
    _max_retries(defaultmaxretries)
    {}
    Status ConnectStatus()
    {
        return _status;
    }
    void Connect()
    {
        _sockfd=socket(AF_INET,SOCK_STREAM,0);
        if(_sockfd<0)
        {
            cerr<<"socket create error"<<endl;
            exit(Exit::SOCKET_ERROR);
        }
        
        struct sockaddr_in server;
        memset(&server,0,sizeof(server));
        server.sin_family=AF_INET;
        server.sin_port=htons(_serverport);
        inet_pton(AF_INET,_serverip.c_str(),&server.sin_addr);

        int n=connect(_sockfd,(struct sockaddr*)&server,sizeof(server));
        if(n<0)
        {
            Disconnect();
            _status=Status::DISCONNECTED;
            return;
        }
        _status=Status::CONNECTED;
    }
    void Reconnect()
    {
        _status=Status::CONNECTING;
        int cnt=0;
        while(true)
        {
            cnt++;
            Connect();
            if(_status==Status::CONNECTED)break;
            if(cnt>=_max_retries)
            {
                cerr<<"重连失败 请检查您网络和IP地址端口号"<<endl;
                _status=Status::CLOSED;
                break;
            }
            cout<<"断线重连中 重连次数："<<cnt<<endl;
            sleep(_retry_interval);
        }
    }
    void Process()//IO通信函数
    {
        while(true)
        {
            sleep(1);
            string message="hello";
            ssize_t n=send(_sockfd,message.c_str(),message.size(),0);
            if(n>0)
            {
                char buffer[1024];
                ssize_t m=recv(_sockfd,buffer,sizeof(buffer)-1,0);
                if(m>0)
                {
                    cout<<"server echo :"<<buffer<<endl;
                }
                else
                {
                    cerr<<"recv error"<<endl;
                    _status=Status::DISCONNECTED;
                    break;
                }
            }
            else
            {
                cerr<<"send error"<<endl;
                _status=Status::DISCONNECTED;
                break;
            }
        }
    }
    void Disconnect()
    {
        if(_sockfd>defaultsockfd)
        {
            ::close(_sockfd);
            _sockfd=defaultsockfd;
            _status=Status::CLOSED;
        }
    }
    ~ClientConnection()
    {}
private:
    int _sockfd;
    uint16_t _serverport;
    string _serverip;
    Status _status;
    int _retry_interval;//重试时间间隔
    int _max_retries;//重试次数

};


class TcpClient
{
public:
    TcpClient(string serverip,uint16_t port):
    _connection(serverip,port)
    {}
    void Excute()
    {
        while(true)
        {
            switch(_connection.ConnectStatus())
            {
                case Status::NEW:
                _connection.Connect();
                break;
                case Status::CONNECTED:
                _connection.Process();
                break;
                case Status::DISCONNECTED:
                _connection.Reconnect();
                break;
                case Status::CLOSED:
                _connection.Disconnect();
                return;
                default:
                break;
            }
        }
    }
    ~TcpClient()
    {}
private:
    ClientConnection _connection;
};

void Usage(string process)
{
    cout<<"usage:"<<process<<" serverip serverport"<<endl;
}
int main(int argc,char *argv[])
{
    if(argc!=3)
    {
        Usage(argv[0]);
        exit(USAGE_ERROR);
    }
    string serverip=argv[1];
    uint16_t serverport=stoi(argv[2]);
    TcpClient client(serverip,serverport);
    client.Excute();
    return 0;
}